import time
import hashlib
from django.core.cache import cache
from user.models import User
from pms import settings


# Debug
if settings.DEBUG:
    cache.set('monkeyhbd', '10000')


class LoginError(Exception):
    def __init__(self, t='_'):
        self.t = t  # Type of error.


class UserNotExist(Exception):
    pass


def get_uid(account, password):
    try:
        user = User.objects.get(id=account)
    except Exception:
        raise LoginError('ACCOUNT_NOT_EXIST')
    # Check password.
    if user.password == password:
        return user.id
    else:
        raise LoginError('WRONG_PASSWORD')


def bin_hash(str1, str2):
    str1 = str(str1)
    str2 = str(str2)
    md5 = hashlib.md5()
    md5.update(str1.encode('utf-8'))
    md5.update(str2.encode('utf-8'))
    return md5.hexdigest()


def gen_token_factor(account, password, cid):
    uid = get_uid(account, password)
    token_factor = bin_hash(uid, time.time())
    token = bin_hash(token_factor, cid)
    cache.set(token, uid)
    # print(token, uid)
    return token_factor


def get_uid_by_token(token):
    # print(token)
    return cache.get(token)


def get_user_by_token(token):
    uid = get_uid_by_token(token)
    user = get_user_by_uid(uid)
    return user


def get_user_by_uid(uid):
    try:
        return User.objects.get(id=uid)
    except Exception:
        raise UserNotExist
